package com.zss.leetcode;

/**
 * 704.二分查找
 * @author fuguozhang
 * @create 2022/5/16
 */
public class BinarySearch1 {

    public static void main(String[] args) {
        int[] nums = new int[]{1,3,6,8,10};
        int res = binarySearch(nums,8);
        System.out.println(res);
    }

    /**
     * 二分查找
     * @param nums 有序数组，升序
     * @param target
     * @return
     */
    public static int binarySearch(int[] nums,int target){
        int left = 0, right = nums.length - 1;
        while(left <= right){
            int mid = left + ((right - left) >> 1);
            if(nums[mid] == target){
                return mid;
            }else if(nums[mid] < target){
                left = mid + 1;
            }else{
                right = mid - 1;
            }
        }
        return -1;
    }
}
